package com.codeerror.demo.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.codeerror.demo.R;
import com.codeerror.demo.bean.TodoBean;
import com.codeerror.demo.util.DateUtil;
import com.codeerror.demo.view.PinkToast;
import com.codeerror.demo.view.SelectDateDialog;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.util.Objects;

public class TodoBsdFragment extends BottomSheetDialogFragment {
    public static TodoBsdFragment instance;
    private long time, startTime, endTime, remindTime;
    private EditText etTitle, etDetail;
    private Button btnCreate;
    private LinearLayout llAddStartTime, llAddEndTime, llAddRemindTime;
    private ImageView ivStartTime, ivEndTime, ivRemindTime;
    private TextView tvStartTime, tvEndTime, tvRemindTime;

    private OnCreateTodoListener onCreateTodoListener;

    public static TodoBsdFragment getInstance() {
        if (null == instance) {
            synchronized (TodoBsdFragment.class) {
                if (null == instance) {
                    instance = new TodoBsdFragment();
                }
            }
        }
        return instance;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        if (getContext() == null) {
            return super.onCreateDialog(savedInstanceState);
        }
        // 设置自定义Bsd样式
        if (getTag() != null) {
            time = Long.parseLong(getTag());
        }
        return new BottomSheetDialog(getContext(), R.style.BottomSheetDialog);
    }

    public interface OnCreateTodoListener {
        void onCreateTodo(TodoBean todoBean);
    }

    public void setOnCreateTodoListener(OnCreateTodoListener onCreateTodoListener) {
        this.onCreateTodoListener = onCreateTodoListener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bsd_add_todo, container, false);
        initView(view);
        // 弹起键盘
        showSoftInput(etTitle);
        llAddStartTime.setOnClickListener(view1 -> {
            new SelectDateDialog.Builder(Objects.requireNonNull(getDialog()).getContext())
                    .setCurTime(System.currentTimeMillis())
                    .setOnSelectDateListener(millis -> {
                        startTime = millis;
                        ivStartTime.setVisibility(View.GONE);
                        tvStartTime.setText(DateUtil.getFormattedTime(millis));
                    }).create().showDialog();
        });
        llAddEndTime.setOnClickListener(view1 -> {
            new SelectDateDialog.Builder(Objects.requireNonNull(getDialog()).getContext())
                    .setCurTime(System.currentTimeMillis())
                    .setOnSelectDateListener(millis -> {
                        endTime = millis;
                        ivEndTime.setVisibility(View.GONE);
                        tvEndTime.setText(DateUtil.getFormattedTime(millis));
                    }).create().showDialog();
        });
        llAddRemindTime.setOnClickListener(view1 ->
                new SelectDateDialog.Builder(Objects.requireNonNull(getDialog()).getContext())
                        .setCurTime(System.currentTimeMillis())
                        .setOnSelectDateListener(millis -> {
                            remindTime = millis;
                            ivRemindTime.setVisibility(View.GONE);
                            tvRemindTime.setText(DateUtil.getFormattedTime(millis));
                        }).create().showDialog());
        btnCreate.setOnClickListener(view1 -> {
            if (TextUtils.isEmpty(etTitle.getText().toString())) {
                new PinkToast.Builder(Objects.requireNonNull(getDialog()).getContext()).setText("待办名称不能为空哦").showToast();
                return;
            }
            TodoBean bean = new TodoBean(etTitle.getText().toString(), time, startTime, endTime, remindTime);
            if (!TextUtils.isEmpty(etDetail.getText().toString())) {
                bean.setDetail(etDetail.getText().toString());
            }
            bean.save();
            onCreateTodoListener.onCreateTodo(bean);
            new PinkToast.Builder(Objects.requireNonNull(getDialog()).getContext()).setText("创建成功").showToast();
            getDialog().dismiss();
        });
        return view;
    }

    private void initView(View view) {
        etTitle = view.findViewById(R.id.et_bsd_add_todo_title);
        etDetail = view.findViewById(R.id.et_bsd_add_todo_detail);
        llAddStartTime = view.findViewById(R.id.ll_bsd_todo_add_start_time);
        llAddEndTime = view.findViewById(R.id.ll_bsd_todo_add_end_time);
        llAddRemindTime = view.findViewById(R.id.ll_bsd_todo_add_remind_time);
        btnCreate = view.findViewById(R.id.btn_bsd_create);
        ivStartTime = view.findViewById(R.id.iv_bsd_add_start_time);
        ivEndTime = view.findViewById(R.id.iv_bsd_add_end_time);
        ivRemindTime = view.findViewById(R.id.iv_bsd_add_remind_time);
        tvStartTime = view.findViewById(R.id.tv_bsd_todo_add_start_time);
        tvEndTime = view.findViewById(R.id.tv_bsd_todo_add_end_time);
        tvRemindTime = view.findViewById(R.id.tv_bsd_todo_add_remind_time);
    }

    /**
     * 弹起键盘
     *
     * @param edit 目标EditText
     */
    private void showSoftInput(EditText edit) {
        // 0.1s后弹起Et获取焦点，弹起软键盘（注意：这里需要有事件间隔软键盘才能正常弹起）
        new Handler().postDelayed(() -> {
            edit.requestFocus();
            InputMethodManager inputMethodManager = (InputMethodManager) edit.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager != null) {
                inputMethodManager.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 100);
    }

    @Override
    public void onStart() {
//        Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onStart();
    }
}
